<template>
  <!-- 头部标签 -->
  <el-tabs
    v-model="editableTabsValue"
    type="card"
    class="demo-tabs"
    closable
    @tab-remove="removeTab"
    @tab-click="tabClick"
  >
    <el-tab-pane
      v-for="item in editableTabs"
      :key="item.name"
      :label="item.title"
      :name="item.name"
    >
      {{ item.content }}
    </el-tab-pane>
  </el-tabs>
</template>


<script setup>
import { ref, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();

let editableTabsValue = ref("");
const editableTabs = ref([
  {
    title: "首页",
    name: "first",
  },
]);

//添加数据
function addTabs(to) {
  editableTabs.value.push({
    title: to.meta.title,
    name: to.name,
  });
}
//监视路由
//获取路由地址 to.path
watch(route, (to) => {
  const flag = editableTabs.value.some((item) => item.title === to.meta.title);
  if (!flag) {
    addTabs(to);
  }
  editableTabsValue.value = to.name;
},{immediate:true});

//点击切换路由
function tabClick(item) {
  router.push({ name: item.props.name });
}

//移除标签操作
const removeTab = (targetName) => {
  console.log(targetName);
  const tabs = editableTabs.value;
  let activeName = editableTabsValue.value;
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.name === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1];
        if (nextTab) {
          activeName = nextTab.name;
          router.push(activeName)
        }
      }
    });
  }

  editableTabsValue.value = activeName;
  editableTabs.value = tabs.filter((tab) => tab.name !== targetName);
};
</script>

<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>